/**
 * 下拉搜索框+分页功能，从服务器获取数据
 * @Date 2023-09-12
 * @author 修改自searchable-select.js www
 */
(function($){
    $.expr[":"].searchableSelectContains = $.expr.createPseudo(function(arg) {
        return function( elem ) {
            return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
        };
    });
    $.searchServerSelect = function(element, options) {
        this.element = element;
        this.options = options || {};
        this.init();

        var _this = this;

        this.searchableElement.click(function(event){
            // event.stopPropagation();
            _this.show();
        }).on('keydown', function(event){
            if (event.which === 13 || event.which === 40 || event.which == 38){
                event.preventDefault();
                _this.show();
            }
        });

        $(document).on('click', null, function(event){
            if(_this.searchableElement.has($(event.target)).length === 0)
                _this.hide();
        });

        //TODO 输入框变化事件
        this.input.on('keydown', function(event){
            event.stopPropagation();
            if(event.which === 13){         //enter
                //按下回车，如果没有选中的项，则查询，否则选中然后关闭
                if(!_this.hasCurrentHoverItem()){
                    //查询
                    _this.filter();
                } else {
                    //选中
                    _this.selectCurrentHoverItem();
                    _this.hide();
                }
            } else if (event.which == 27) { //ese
                _this.hide();
            } else if (event.which == 40) { //down
                _this.hoverNextItem();
            } else if (event.which == 38) { //up
                _this.hoverPreviousItem();
            }
        }).on('keyup', function(event){
            if(_this.inputOldValue === _this.input.val()){ //防止按下其他键带来的影响
                return;
            }
            //输入内容变化，那么再次回车应该触发搜索而不是选中
            if(event.which != 13 && event.which != 27 && event.which != 38 && event.which != 40){
                _this.cancelHover()
            }
        })
    }

    var $sS = $.searchServerSelect;

    $sS.fn = $sS.prototype = {
        version: '0.0.1'
    };

    $sS.fn.extend = $sS.extend = $.extend;

    $sS.fn.extend({
        //初始化
        init: function(){
            var _this = this;
            this.element.hide();
            this.searchableElement = $('<div tabindex="0" class="searchable-select"></div>');
            this.holder = $('<div class="searchable-select-holder"></div>');
            this.dropdown = $('<div class="searchable-select-dropdown searchable-select-hide"></div>');
            this.input = $('<input type="text" class="searchable-select-input" style="width: 80%" />');
            this.queryBtn = $('<input type="button" class="queryBtn" value="查询" />');
            this.inputOldValue = '';//控制查询频率
            this.items = $('<div class="searchable-select-items"></div>');
            this.caret = $('<span class="searchable-select-caret"></span>');
            this.clear = $('<span class="searchable-select-clear">×</span>');

            this.scrollPart = $('<div class="searchable-scroll"></div>');
            this.pager = $('<div class="searchable-pager"></div>');
            //当前高亮
            this.currentHoverItem = false;
            //当前选中
            this.currentSelectedItem = false;
            this.queryBtn.click(function () {
                _this.filter(true)
            })
            this.clear.click(function (event) {
                event.stopPropagation();
                _this.cancelSelected()
            })

            this.dropdown.append(this.input);
            this.dropdown.append(this.queryBtn);//查询按钮
            this.dropdown.append(this.scrollPart);

            this.scrollPart.append(this.items);
            this.scrollPart.append(this.pager);

            this.searchableElement.append(this.caret);
            this.searchableElement.append(this.clear);
            this.searchableElement.append(this.holder);
            this.searchableElement.append(this.dropdown);
            this.element.after(this.searchableElement);

            this.buildItems();
        },

        /**
         * 2023/09/27：设置值：参考filter
         * @param value 设置的值
         * @param label 显示值
         */
        set:function(value,label){
            this.holder.text(label?label:value)
            $(this.element).val(value);
        },

        //TODO 触发搜索
        filter: function(btnClick=false){
            let _this = this;
            if(!btnClick && _this.inputOldValue === _this.input.val()){ //防止按下其他键带来的影响
                return;
            }
            _this.inputOldValue = _this.input.val()
            _this.buildItems();
        },

        //TODO 初始化添加项
        buildItems: function(pageIndex = 1,pageSize = 10){
            var _this = this;
            let keyword = _this.input.val();
            let promise = _this.getSelectData(keyword,pageIndex,pageSize)
            let loading = $('<span class="searchable-loading">loading...</span>')
            _this.pager.append(loading);
            promise.then(function (data) {//回调成功
                //清空原有内容
                $(_this.items).html('');
                _this.buildPager(data)
                let dataList = data.data
                _this.currentHoverItem = false;
                if(dataList && dataList.length>0){
                    for (let i = 0; i < dataList.length; i++) {
                        var item = $('<div class="searchable-select-item" data-value="'+dataList[i].value+'">'+dataList[i].label+'</div>');

                        //如果选中的和当前的相等,则高亮
                        if(_this.currentSelectedItem && $(_this.currentSelectedItem).html() === dataList[i].label){
                            _this.selectItem(item);
                            _this.hoverItem(item);
                        }

                        item.on('mouseenter', function(){
                            $(this).addClass('hover');
                        }).on('mouseleave', function(){
                            $(this).removeClass('hover');
                        }).click(function(event){
                            event.stopPropagation();
                            _this.selectItem($(this));
                            _this.hide();
                        });

                        _this.items.append(item);
                    }
                }
            },function (err) {
                console.log("服务器获取数据失败! ",err)
                $(loading).remove()
                //失败提示
                loading = $('<span class="searchable-loading" style="background-color: #e28a8a">加载失败,请稍后</span>')
                _this.pager.append(loading);
                setTimeout(function () {
                    $(loading).remove()
                },3000)
            })
        },
        //渲染分页内容
        buildPager:function(pager){
            let _this = this;
            let thisPager = _this.pager;
            //清空内容
            $(thisPager).html('')

            $(thisPager).append(`<span class="searchable-pager-item fl">共${pager.itemCount}条</span>`)
            if(pager.itemCount>0){
                let pageCount = Math.ceil(pager.itemCount / pager.pageSize)
                //渲染5个页码,最好是单数
                let showPageBtnCount = 5;

                let min = pager.pageIndex
                let max = pager.pageIndex
                while (max - min + 1 < showPageBtnCount){
                    if(min>1){
                        min -- ;
                    }if(max<pageCount){
                        max++;
                    }
                    if(min===1 && max===pageCount){
                        break;
                    }
                }
                let items = $('<div class="fr"></div>')

                for (let i = min; i <= max; i++) {
                    let item
                    if(pager.pageIndex===i){
                        item = $(`<a class="searchable-pager-item searchable-pager-item-active">${i}</a>`);
                    }else{
                        item = $(`<a class="searchable-pager-item">${i}</a>`);
                        item.click(function(event){
                            //取消原来的点击事件，防止弹框消失
                            event.stopPropagation();
                            _this.buildItems(i,pager.pageSize)
                        });
                    }
                    $(items).append(item)
                }
                $(thisPager).append(items)
            }
        },

        //TODO 获取数据，服务器
        getSelectData:function(keywords,pageIndex = 1,pageSize = 10){

            console.log(`getSelectData(${keywords},${pageIndex},${pageSize}) `)

            if(!this.options.getDataFunction){
                alert("未设置数据获取逻辑：getDataFunction")
            }
            return this.options.getDataFunction(keywords,pageIndex,pageSize);
        },

        show: function(){
            this.dropdown.removeClass('searchable-select-hide');
            this.input.focus();
            this.status = 'show';
            this.dropdown.css('z-index', 100); //打开下拉列表时调高z-index层级
        },

        hide: function(){
            if(!(this.status === 'show'))
                return;

            if(this.items.find(':not(.searchable-select-hide)').length === 0)
                this.input.val('');
            this.dropdown.addClass('searchable-select-hide');
            this.searchableElement.trigger('focus');
            this.status = 'hide';
            this.dropdown.css('z-index', 1); //关闭下拉列表时恢复z-index层级
        },

        //高亮第一个
        hoverFirstNotHideItem: function(){
            this.hoverItem(this.items.find('.searchable-select-item:not(.searchable-select-hide)').first());
        },
        //选中高亮
        selectCurrentHoverItem: function(){
            if(!this.currentHoverItem.hasClass('searchable-select-hide'))
                this.selectItem(this.currentHoverItem);
        },
        //高亮覆盖，向前加载
        hoverPreviousItem: function(){
            if(!this.hasCurrentHoverItem())
                this.hoverFirstNotHideItem();
            else{
                var prevItem = this.currentHoverItem.prevAll('.searchable-select-item:not(.searchable-select-hide):first')
                if(prevItem.length > 0)
                    this.hoverItem(prevItem);
            }
        },
        //高亮覆盖，向后加载
        hoverNextItem: function(){
            if(!this.hasCurrentHoverItem())
                this.hoverFirstNotHideItem();
            else{
                var nextItem = this.currentHoverItem.nextAll('.searchable-select-item:not(.searchable-select-hide):first')
                if(nextItem.length > 0)
                    this.hoverItem(nextItem);
            }
        },
        hasCurrentSelectedItem: function(){
            return this.currentSelectedItem && this.currentSelectedItem.length > 0;
        },

        selectItem: function(item){
            console.log("selectItem:",$(item)[0].innerHTML)
            if(this.hasCurrentSelectedItem())
                this.currentSelectedItem.removeClass('selected');

            this.currentSelectedItem = item;
            item.addClass('selected');

            this.hoverItem(item);

            this.holder.text(item.text());
            var value = item.data('value');
            this.holder.data('value', value);
            this.element.val(value);

            if(this.options.afterSelectItem){
                this.options.afterSelectItem.apply(this);
            }
        },

        hasCurrentHoverItem: function(){
            return this.currentHoverItem && this.currentHoverItem.length > 0;
        },

        hoverItem: function(item){
            if(this.hasCurrentHoverItem())
                this.currentHoverItem.removeClass('hover');

            if(item.outerHeight() + item.position().top > this.items.height())
                this.items.scrollTop(this.items.scrollTop() + item.outerHeight() + item.position().top - this.items.height());
            else if(item.position().top < 0)
                this.items.scrollTop(this.items.scrollTop() + item.position().top);

            this.currentHoverItem = item;
            item.addClass('hover');
        },
        //取消hover
        cancelHover:function(){
            if(this.hasCurrentHoverItem()){
                this.currentHoverItem.removeClass('hover');
                this.currentHoverItem = false;
            }
        },
        //取消选中
        cancelSelected:function () {
            if(this.hasCurrentSelectedItem()){
                this.currentSelectedItem.removeClass('selected');
                this.currentSelectedItem = false
            }
            this.element.val('')
            this.holder.text('')
            this.holder.data('value', '');
        }
    });

    //TODO 如果只有一个元素，则返回创建的下拉框组件，否则返回数组
    $.fn.searchServerSelect = function(options,getDataFunction){
        options.getDataFunction = getDataFunction;
        let res = []
        this.each(function(){
            var sS = new $sS($(this), options);
            res.push(sS)
        });
        if(res.length === 1){
            return res[0]
        }
        return res;
        // return this;
    };

})(jQuery);
